const createError = require('http-errors');
const express = require('express');
const bodyParser = require('body-parser')
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const app = express();
// 改写
const http = require('http');
const server = http.createServer(app);
// 引入的路由
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const followRouter = require('./routes/follow');
const newRouter = require('./routes/news');

// 中间件
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// post请求中间件
app.use(bodyParser.urlencoded({ extended: true }));
//配置CORS，指定放行的域名，防止出现跨域问题
const cors = require('cors')
app.use(cors({
  origin: "*"
}));

// 挂载路由
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/follow', followRouter);
app.use('/news', newRouter);

//错误处理中间件
app.use((err, req, res, next) => {
  //err 接收到的路由传递过来的错误
  console.log(err)
  //响应500，服务器端错误
  res.send({ code: 500, msg: '服务器端错误' })
})

server.listen(3000, () => {
  console.log('server is running...');
});
